package com.client.demo;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap.*;


import java.io.IOException;
import java.util.*;

public class SendBasic {
	public static void main(String[] args) throws IOException, URISyntaxException {
		//viewResponse();
		HashMap<String, String> map = new HashMap<>();
		map.put("name", "jack");
		map.put("password", "123");
		sendGetByParams("http://localhost:8080/hello",map);
		//sendPostRequest("http://127.0.0.1:8080/post");
		//sendJSONPost("http://127.0.0.1:8080/jsonPost");
		//disable302("http://localhost:8080/jsonPost");
	}

	private static void disable302(String url) throws IOException {
		HttpGet request = new HttpGet(url);
		request.addHeader(HttpHeaders.USER_AGENT, "Google");

		try (
				CloseableHttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling().build();
				final CloseableHttpResponse response = httpClient.execute(request)
		) {
			System.out.println(response.getProtocolVersion()); // HTTP/1.1
			System.out.println(response.getStatusLine().getStatusCode()); // 301
			System.out.println(response.getStatusLine().getReasonPhrase()); //  Moved Permanently
			System.out.println(response.getStatusLine().toString()); // HTTP/1.1 301 Moved Permanently
		}
	}

	/**
	 * Send JSON POST Request
	 *
	 * @param url
	 * @throws IOException
	 */
	private static void sendJSONPost(String url) throws IOException {
		HttpPost post = new HttpPost(url);
		StringBuilder json = new StringBuilder();
		json.append("{");
		json.append("\"username\":\"mkyong\",");
		//json.append("\"password\":\"hello\",");
		json.append("\"password\":\"hello\"");
		//json.append("\"custom\":\"hello\"");
		json.append("}");
		post.setEntity(new StringEntity(json.toString()));

		try (CloseableHttpClient httpClient = HttpClients.createDefault();
		     CloseableHttpResponse response = httpClient.execute(post)) {
			final String result = EntityUtils.toString(response.getEntity());
			System.out.println(result);
		}
	}

	private static void sendPostRequest(String url) throws IOException {
		String result = "";
		HttpPost post = new HttpPost(url);
		ArrayList<NameValuePair> urlParameters = new ArrayList<>();
		urlParameters.add(new BasicNameValuePair("username", "admin"));
		urlParameters.add(new BasicNameValuePair("password", "123"));
		urlParameters.add(new BasicNameValuePair("custom", "secret"));

		UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(urlParameters);
		post.setEntity(urlEncodedFormEntity);
		//Close with try-with-resources.
		try (CloseableHttpClient httpClient = HttpClients.createDefault();
		     CloseableHttpResponse response = httpClient.execute(post)) {
			result = EntityUtils.toString(response.getEntity());
		}
		System.out.println(result);
		//return result;
	}


	private static void viewResponse() throws IOException {
		System.out.println("=========viewResponse=====");
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet request = new HttpGet("http://localhost:8080/hello");
		try {
			CloseableHttpResponse response = httpClient.execute(request);
			try {
				System.out.println(response.getProtocolVersion()); //http/1.1
				System.out.println(response.getStatusLine().getStatusCode()); //200
				System.out.println(response.getStatusLine().getReasonPhrase()); // OK
				System.out.println(response.getStatusLine().toString()); // http1.1 200 OK
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String res = EntityUtils.toString(entity);
					System.out.println(res);
				}
			} finally {
				response.close();
			}
		} finally {
			httpClient.close();
			System.out.println("=========viewResponse=====");
		}
	}

	private static void sendGetByParams(final String url, HashMap<String,String> map) throws IOException, URISyntaxException {
		CloseableHttpClient httpClient = HttpClients.createDefault();

		try {

			final URIBuilder builder = new URIBuilder(url);

			for (String key : map.keySet()) {
				builder.addParameter(key,map.get(key));
			}
			HttpGet request = new HttpGet(builder.build());
			CloseableHttpResponse response = httpClient.execute(request);
			try {
				System.out.println(response);
			} finally {
				response.close();
			}
		} finally {
			httpClient.close();

		}

	}
}
